﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevLib.Data;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace sqltomongo
{
    public class SQLServerDb : DbHelper
    {
        public static bool IsSQLServer { get; set; } = System.Configuration.ConfigurationManager.AppSettings["db_type"].ToLower() == "mysql";
        private static SQLServerDb sqlServerDb = null;
        public static string SQLConnection { get; } = System.Configuration.ConfigurationManager.ConnectionStrings["sql_conn"].ConnectionString;
        public static string MySQLConnection { get; set; } = System.Configuration.ConfigurationManager.ConnectionStrings["mysql_conn"].ConnectionString;
       
        private static string GetSQLConnection() {
            if (!IsSQLServer)
            {
                return MySQLConnection;
            }
            else
            {
                return SQLConnection;
            }
        }
        private SQLServerDb() : base(GetSQLConnection(), IsSQLServer? DbProvider.SqlServer: DbProvider.MySQL) { }

        public static SQLServerDb Instance()
        {
            if (sqlServerDb == null)
            {
                return new SQLServerDb();
            }
            return null;
        }
        public string Sql { get; set; } = ConfigurationManager.AppSettings["sql_statement"];

        public DataSet ExecuteSQLDataSet(string SQLString)
        {
            DataSet result;
            using (SqlConnection connection = new SqlConnection(SQLConnection)) 
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlCommand cmd = new SqlCommand(SQLString);
                    cmd.CommandTimeout = 9999999;
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = connection;
                    SqlDataAdapter command = new SqlDataAdapter(cmd);
                    command.Fill(ds, "ds");
                }
                catch (SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                result = ds;
            }
            return result;
        }
    }
}
